import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { ValidationPipe, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { AppModule } from './app.module';
import { AppConfig } from './config/app.config';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';

async function bootstrap() {
  const logger = new Logger('Bootstrap');
  
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: ['log', 'error', 'warn', 'debug', 'verbose'],
  });

  // 获取配置服务
  const configService = app.get(ConfigService<AppConfig>);
  const port = configService.get('port', { infer: true });
  const nodeEnv = configService.get('nodeEnv', { infer: true });

  // 配置静态文件服务
  // 之前使用 join(__dirname, '..', 'uploads') 在构建后指向 dist/uploads，而上传逻辑使用相对路径 ./uploads
  // (即 process.cwd()/uploads)，导致生产环境或构建后访问 /uploads/* 返回 404。
  // 统一改为基于运行时工作目录 process.cwd() 的 uploads 目录，确保与上传保存路径一致。
  const staticUploadsPath = join(process.cwd(), 'uploads');
  app.useStaticAssets(staticUploadsPath, {
    prefix: '/uploads', // 去掉尾部斜杠，Express 同样匹配 /uploads/*
  });
  logger.log(`📁 Serving uploads from: ${staticUploadsPath}`);

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

  // CORS 配置 - 允许所有来源
  app.enableCors({
    origin: '*',  // 允许所有来源
    credentials: false,  // 当origin为*时，credentials必须为false
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'x-api-key'],
  });

  // Swagger 文档配置
  if (nodeEnv === 'development') {
    const config = new DocumentBuilder()
      .setTitle('C4pad Fun API')
      .setDescription('Backend API for C4pad Fun - Solana Token Launch Platform')
      .setVersion('1.0')
      .addTag('tokens', 'Token management operations')
      .addTag('health', 'Health check endpoints')
      .addTag('websocket', 'Real-time WebSocket events')
      .addBearerAuth()
      .addServer(`http://localhost:${port}`, 'Local Development')
      .build();

    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api/docs', app, document, {
      swaggerOptions: {
        persistAuthorization: true,
        tagsSorter: 'alpha',
        operationsSorter: 'alpha',
      },
    });

    logger.log(`📚 Swagger documentation available at: http://localhost:${port}/api/docs`);
  }

  // 启动应用
  await app.listen(port);

  logger.log(`🚀 Server running on: http://localhost:${port}`);
  logger.log(`🌍 Environment: ${nodeEnv}`);
  logger.log(`📊 Health check: http://localhost:${port}/api/health`);
  
  if (nodeEnv === 'development') {
    logger.log(`🔗 WebSocket: ws://localhost:${port}/realtime`);
  }
}

bootstrap().catch((error) => {
  console.error('Failed to start application:', error);
  process.exit(1);
});
